﻿/// ****************************************************************************
/// Author:	        Robin Zhu
/// Create Date:	2013-12-13
/// Purpose: 		用户，角色，权限三者关系的缓存类
/// ****************************************************************************
/// Modify By		Date			Remark
/// ****************************************************************************
/// 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RB.Web.Security.Rdb
{
    public static class UserRolePermissionCache
    {
        private static object _locker = new object();

        private static Dictionary<Guid, ILookup<string, Guid>> _cache = new Dictionary<Guid, ILookup<string, Guid>>();

        public static Guid GetRoleId(Guid userId, string permCode)
        {
            lock (_locker)
            {
                Guid role = Guid.Empty;
                ILookup<string, Guid> permRoles = null;
                if (!_cache.TryGetValue(userId, out permRoles))
                {
                    var q = from t in (new UserAccountRoleSet()).AsQueryable()
                            join t1 in (new RolePermissionSet()).AsQueryable()
                            on t.RoleId equals t1.RoleId
                            where t.UserId == userId
                            select new { t1.PermCode, t.RoleId };
                    permRoles = q.ToLookup(p => p.PermCode, p => p.RoleId);
                    _cache.Add(userId, permRoles);
                }
                if (permRoles != null)
                    role = permRoles[permCode].FirstOrDefault();

                return role;
            }
        }

        public static void ClearCache()
        {
            lock(_locker)
            {
                _cache.Clear();
            }
        }
    }
}
